package com.parking.action;

import com.parking.dto.SystemAdminDto;
import com.parking.service.SystemAdminService;
import com.parking.service.impl.SystemAdminServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/account")
public class AccountServlet extends HttpServlet {
    private SystemAdminService systemAdminService=new SystemAdminServiceImpl();
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        String method =request.getParameter("method");
        switch (method){
            case "login":
                String username=request.getParameter("username");
                String password=request.getParameter("password");
                SystemAdminDto userDto = this.systemAdminService.login(username,password);
                switch (userDto.getCode()){
                    case -1:
                        request.setAttribute("usernameError","用户名不存在");
                        request.getRequestDispatcher("login.jsp").forward(request,response);
                        break;
                    case -2:
                        request.setAttribute("passwordError","密码错误");
                        request.getRequestDispatcher("login.jsp").forward(request,response);
                        break;
                    case 0:
                        HttpSession session =request.getSession();
                        session.setAttribute("User",userDto.getUser());
                        response.sendRedirect("user.jsp");
                        break;
                }
                break;
            case "logout":
                request.getSession().invalidate();
                response.sendRedirect("login.jsp");
                break;
        }
    }
}
